//
//  JCOauthController.swift
//  weibo07777
//
//  Created by mac on 15/12/18.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
class JCOauthController: UIViewController ,UIWebViewDelegate{
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = JCNetWorkTool.sharedInstance.oauthURL()
        
        webView.loadRequest(NSURLRequest(URL: url))
        
        // MARK :setting 导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
    }
    
    @objc private func autoFill(){
        
        let js = "document.getElementById('userId').value='j_dreamcatcher@163.com'; document.getElementById('passwd').value='AMNZQQ';"
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    @objc private func dismiss(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    
    // MARK :webView Delegate
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL);

        if !request.URL!.absoluteString.hasPrefix(JCNetWorkTool.sharedInstance.redirect_uri){
            return true
        }
        
        if let query = request.URL?.query{
            SVProgressHUD.dismiss()
            let codeStr = "code"
            if query.hasPrefix(codeStr){
                
                print("点击授权\(query)")
                let code = query.componentsSeparatedByString("=").last!
                // loadAccessToken
                self.loadAccessToken(code)
            }
            else{
                print("点击了取消")
                self.dismiss()
            }
        }
        
        return false
    }
    
    func loadAccessToken(code :String){
        
        JCNetWorkTool.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            // 出错
            if error != nil || result == nil{
                self.dismiss()
            }
            // 成功
            else{
                
                let userAccount = JCUserAccount(dic: result!)
                userAccount.saveAccout()
                print("userAccount:\(userAccount)")
                
                self.dismiss()
                AppDelegate.switchRootViewController(false)
            }
        }
        
    }
    
    private func changeVc(){
        UIApplication.sharedApplication().keyWindow?.rootViewController
    }
    
    // MARK : lazy
    private lazy var webView = UIWebView()
}
